﻿using System;
using System.Collections;
using Unity.VisualScripting;
using UnityEngine;

public class Timer
{
    #region 属性
    // 持续次数 -1代表无限次
    private int continueCount;
    private float duration;
    private event Action OnTimerWake, OnTimerStart, OnTimerUpdate, OnTimerDone, OnTimerComplete;

    #endregion
    #region 状态
    private int _id = -1;
    public int ID
    {
        get 
        {
            if( _id == -1)
            {
                _id = TimerManager.Instance.GetTimerID();
            }
            return _id; 
        }
        set { _id = value; }
    }
    private float startTime;
    private float targetTime;
    private bool isActive;
    private bool isCompleted = false;
    private float remainderTime;
    private int remainderCount;
    #endregion

    public Timer(float duration, int continueCount = 1)
    {
        this.continueCount = continueCount;
        this.remainderCount = continueCount;
        this.duration = duration;
    }
    public void Init(Action wakeAction = null, Action startAction = null, Action updateAction = null, Action doneAction = null, Action completeAction = null)
    {
        OnTimerWake += wakeAction;
        OnTimerStart += startAction;
        OnTimerUpdate += updateAction;
        OnTimerDone += doneAction;
        OnTimerComplete += completeAction;
    }
    public bool GetTimerActive()
    {
        return isActive;
    }
    public bool GetTimerCompleteState()
    {
        return isCompleted;
    }
    public void WakeTimer()
    {
        OnTimerWake?.Invoke();
    }
    public void StartTimer()
    {
        startTime = Time.time;
        targetTime = startTime + duration;
        isActive = true;
        OnTimerStart?.Invoke();
    }
    public void StopTimer()
    {
        isActive = false;
        isCompleted = true;
        OnTimerComplete?.Invoke();
    }
    public void PauseTimer()
    {
        isActive = false;
        this.remainderTime = duration - (Time.time - startTime);
    }
    public void CancelPauseTimer()
    {
        startTime = Time.time;
        targetTime = startTime + remainderTime;
        remainderTime = 0;
        isActive = true;
    }
    public void RestartTimer()
    {
        StartTimer();
    }
    public void ResetTimer()
    {
        this.remainderCount = this.continueCount;
        isCompleted = true;
        StartTimer();
    }
    public void Tick()
    {
        if (!isActive || isCompleted) return;
        OnTimerUpdate?.Invoke();
        if (Time.time >= targetTime)
        {
            OnTimerDone?.Invoke();
            this.remainderCount = this.remainderCount == -1 ? -1 : --this.remainderCount;
            if (this.remainderCount == -1 || this.remainderCount > 0)
            {
                StartTimer();
            }
            else
            {
                StopTimer();
            }
        }
    }
}